package com.gmall.coupon.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gmall.common.result.Result;
import com.gmall.coupon.mapper.CouponInfoMapper;
import com.gmall.coupon.mapper.CouponUseMapper;
import com.gmall.model.activity.CouponInfo;
import com.gmall.model.activity.CouponUse;
import com.gmall.model.activity.dto.SkuCoupon;
import com.gmall.model.enums.CouponStatus;
import com.gmall.model.enums.CouponType;
import com.gmall.model.product.SkuInfo;
import com.gmall.product.feign.ProductApiFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class CouponUserService {

    @Autowired
    CouponInfoMapper couponInfoMapper;
    @Autowired
    CouponUseMapper couponUseMapper;
    @Autowired
    ProductApiFeignClient productApiFeignClient;

    public Result<List<SkuCoupon>> getCouponListBySkuId(Long userId,
                                                Long skuId,Integer skuNum) {

        //根据SKUID 查询 spuID，tmID，categoryID
        /**
         * -- 根据 SKUID 找到可以使用的优惠券
         * -- skuID 找到 spuID，品牌ID，分类ID
         * -- skuid = 19  spuId = 7 tmID = 3 categoryId = 192
         */
        Result<SkuInfo> skuInfo_result = productApiFeignClient.getSkuInfoById(skuId);
        if(skuInfo_result.isOk()){

            SkuInfo skuInfo = skuInfo_result.getData();
            List<SkuCoupon> couponList = couponInfoMapper.getCouponListBySku(userId, skuId,
                    skuInfo.getSpuId(), skuInfo.getTmId(), skuInfo.getCategory3Id());
            BigDecimal totalAmount
                    = skuInfo.getPrice().multiply(new BigDecimal(skuNum));//总金额

            for(int i=0;i<couponList.size();i++){
                SkuCoupon skuCoupon = couponList.get(i);//
                skuCoupon.setPayAmount(totalAmount);
                if(skuCoupon.getCouponType().equals(CouponType.FULL_REDUCTION.toString())){
                    if(totalAmount.compareTo(skuCoupon.getConditionAmount())>=0){//满足满减
                        BigDecimal benefitAmount = skuCoupon.getBenefitAmount();
                        skuCoupon.setPayAmount(totalAmount.subtract(benefitAmount));
                    }
                }
                else if(skuCoupon.getCouponType().equals(CouponType.FULL_DISCOUNT.toString())){
                    if(skuNum >= skuCoupon.getConditionNum()){//满足满量
                        double discount = skuCoupon.getBenefitDiscount().doubleValue() * 0.1;
                        skuCoupon.setPayAmount(totalAmount.multiply(new BigDecimal(discount)));
                    }
                }
                else if(skuCoupon.getCouponType().equals(CouponType.CASH.toString())){
                    BigDecimal benefitAmount = skuCoupon.getBenefitAmount();
                    skuCoupon.setPayAmount(totalAmount.subtract(benefitAmount));
                }
                else if(skuCoupon.getCouponType().equals(CouponType.DISCOUNT.toString())){
                    double discount = skuCoupon.getBenefitDiscount().doubleValue() * 0.1;
                    skuCoupon.setPayAmount(totalAmount.multiply(new BigDecimal(discount)));
                }
            }
            return Result.ok(couponList);
        }
        return Result.fail();
    }

    public Result<SkuCoupon> getCheckedCouponBySkuId(Long userId, Long skuId, Integer skuNum) {
        //根据SKUID 查询 spuID，tmID，categoryID
        Result<SkuInfo> skuInfo_result = productApiFeignClient.getSkuInfoById(skuId);
        if(skuInfo_result.isOk()){
            SkuInfo skuInfo = skuInfo_result.getData();
            List<SkuCoupon> couponList = couponInfoMapper.getCouponListBySku(userId, skuId,
                    skuInfo.getSpuId(), skuInfo.getTmId(), skuInfo.getCategory3Id());

            BigDecimal totalAmount
                    = skuInfo.getPrice().multiply(new BigDecimal(skuNum));//总金额
            SkuCoupon skuCouponCheked = null;

            if(couponList.size()>0) {
                BigDecimal checkedAmount = totalAmount;//支付的最优金额，最小的支付金额
                for(int i=0;i<couponList.size();i++){
                    SkuCoupon skuCoupon = couponList.get(i);//
                    skuCoupon.setPayAmount(totalAmount);
                    if(skuCoupon.getCouponType().equals(CouponType.FULL_REDUCTION.toString())){
                        if(totalAmount.compareTo(skuCoupon.getConditionAmount())>=0){//满足满减
                            BigDecimal benefitAmount = skuCoupon.getBenefitAmount();//优惠金额
                            BigDecimal payAmount = totalAmount.subtract(benefitAmount);
                            skuCoupon.setPayAmount(payAmount);
                            if(payAmount.compareTo(checkedAmount)<0){
                                checkedAmount = payAmount;
                                skuCouponCheked = skuCoupon;
                            }
                        }
                    }
                    else if(skuCoupon.getCouponType().equals(CouponType.FULL_DISCOUNT.toString())){
                        if(skuNum >= skuCoupon.getConditionNum()){//满足满量
                            double discount = skuCoupon.getBenefitDiscount().doubleValue() * 0.1;
                            BigDecimal payAmount = totalAmount.multiply(new BigDecimal(discount));
                            skuCoupon.setPayAmount(payAmount);
                            if(payAmount.compareTo(checkedAmount)<0){
                                checkedAmount = payAmount;
                                skuCouponCheked = skuCoupon;
                            }
                        }
                    }
                    else if(skuCoupon.getCouponType().equals(CouponType.CASH.toString())){
                        BigDecimal benefitAmount = skuCoupon.getBenefitAmount();
                        BigDecimal payAmount = totalAmount.subtract(benefitAmount);
                        skuCoupon.setPayAmount(payAmount);
                        if(payAmount.compareTo(checkedAmount)<0){
                            checkedAmount = payAmount;
                            skuCouponCheked = skuCoupon;
                        }

                    }
                    else if(skuCoupon.getCouponType().equals(CouponType.DISCOUNT.toString())){
                        double discount = skuCoupon.getBenefitDiscount().doubleValue() * 0.1;
                        BigDecimal payAmount = totalAmount.multiply(new BigDecimal(discount));
                        skuCoupon.setPayAmount(payAmount);
                        if(payAmount.compareTo(checkedAmount)<0){
                            checkedAmount = payAmount;
                            skuCouponCheked = skuCoupon;
                        }
                    }
                }
            }

            if(skuCouponCheked != null){//找到了最优的优惠卷
                return Result.ok(skuCouponCheked);
            }
        }
        return Result.fail();
    }


    @Transactional(isolation = Isolation.REPEATABLE_READ)
    public Result<String> getCouponInfo(Long couponId, Long userId) {

        CouponInfo couponInfo = couponInfoMapper.selectById(couponId);
        QueryWrapper<CouponUse> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(CouponUse::getUserId,userId)
                .eq(CouponUse::getCouponId,couponId);
        List<CouponUse> couponUseList = couponUseMapper.selectList(queryWrapper);
        if(couponUseList.size()>0){
            return Result.fail("不能重复领取");
        }
        CouponUse couponUse = new CouponUse();
        couponUse.setCouponId(couponId);
        couponUse.setUserId(userId);
        couponUse.setCouponStatus(CouponStatus.NOT_USED.name());
        couponUse.setGetTime(new Date());
        couponUse.setExpireTime(couponInfo.getExpireTime());
        couponUseMapper.insert(couponUse);

        couponInfo.setTakenCount(couponInfo.getTakenCount()+1);
        couponInfoMapper.updateById(couponInfo);
        return Result.ok();
    }

    public Result<String> useCoupon(Long couponId, Long userId, Long orderId) {

        QueryWrapper<CouponUse> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CouponUse::getUserId,userId);
        queryWrapper.lambda().eq(CouponUse::getCouponId,couponId);
        List<CouponUse> couponUses = couponUseMapper.selectList(queryWrapper);
        if(couponUses.size()>0){
            CouponUse couponUse = couponUses.get(0);
            couponUse.setCouponStatus(CouponStatus.USE_RUN.name());
            couponUse.setOrderId(orderId);
            couponUse.setUsingTime(new Date());
            couponUseMapper.updateById(couponUse);
            return Result.ok();
        }
        return Result.fail("优惠券不存在");
    }

    public Result<String> unUseCoupon(Long orderId) {

        System.out.println("===================unUseCoupon ");
        return Result.ok();
    }
}
